package com.source.lightfowl.basedata.service.impl;

import com.source.lightfowl.DTO.StallsDownloadDTO;
import com.source.lightfowl.DTO.StallsUploadDTO;
import com.source.lightfowl.VO.StallsVO;
import com.source.lightfowl.basedata.dao.BarcodeMachineDao;
import com.source.lightfowl.basedata.dao.SlaughterHouseDao;
import com.source.lightfowl.basedata.dao.StallsDao;
import com.source.lightfowl.basedata.entity.BarcodeMachine;
import com.source.lightfowl.basedata.entity.SlaughterHouse;
import com.source.lightfowl.basedata.entity.Stalls;
import com.source.lightfowl.basedata.service.StallsService;
import com.source.lightfowl.constant.ImageCatalogue;
import com.source.lightfowl.handler.MyException;
import com.source.lightfowl.labelingRecord.dao.RecordDao;
import com.source.lightfowl.person.dao.PersonDao;
import com.source.lightfowl.person.entity.Person;
import com.source.lightfowl.person.entity.UsersExtends;
import com.source.lightfowl.utils.ImageUtil;
import com.source.lightfowl.utils.StringTOArrayList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.*;

/**
 * @Author: cxy
 * @Description: 屠宰档口
 */
@Service
public class StallsServiceImpl implements StallsService {

    @Autowired
    private StallsDao stallsDao;
    @Autowired
    private PersonDao personDao;
    @Autowired
    private RecordDao recordDao;
    @Autowired
    private SlaughterHouseDao slaughterHouseDao;
    @Autowired
    private BarcodeMachineDao barcodeMachineDao;

    @Override
    public List<StallsVO> findAll(int state) {
        List<Stalls> list = stallsDao.findByState(state);
        return changeToVOList(list);
    }

    @Override
    public Page<Stalls> findAllPage(int page, int pageNum) {
        return stallsDao.findAll(PageRequest.of(page - 1, pageNum));
    }

    @Override
    public Page<StallsVO> findAllPageVO(Integer state, int page, int pageNum) {
        Page<Stalls> stallsPage = stallsDao.findByState(state, PageRequest.of(page - 1, pageNum));
        List<StallsVO> list = new LinkedList<>();
        for (Stalls s :
                stallsPage.getContent()) {
            StallsVO vo = new StallsVO();
            BeanUtils.copyProperties(s, vo);
            list.add(vo);
        }
        return new PageImpl<StallsVO>(list, PageRequest.of(page - 1, pageNum), stallsPage.getTotalElements());
    }

    @Override
    public Optional<Stalls> findById(Integer id) {
        return stallsDao.findById(id);
    }

    //这个方法是查询详情用的 本来查询详情是使用第一个版本  但是需要添加一些字段 所以需要返回vo 改了vo之后发现别的地方也使用到这个方法 所以原来的方法返回类型不能修改了 否则要大改。所以添加个方法 查询详情
    @Override
    public StallsVO findByIdVersion2(Integer id) {
        Optional<Stalls> optional = stallsDao.findById(id);
        if (optional.isPresent()) {
            Stalls s = optional.get();
            return changeToVO(s);
        }
        return new StallsVO();
    }


    @Override
    public StallsVO findByIdVO(Integer id) {
        Stalls s = stallsDao.findByIdAndStateNot(id, 0);
        return changeToVO(s);
    }

    @Override
    public void save(Stalls sh, MultipartFile file, HttpServletRequest request) {
        if (sh.getCreateDate() == null || sh.getCreateDate().equals("")) {
            sh.setCreateDate(new Date());
        }
        if (file != null) {
            String s = null;
            try {
                s = ImageUtil.saveImage(file, ImageCatalogue.Stalls_Catalogue);
            } catch (Exception e) {
                System.out.println("图片保存异常");
                System.out.println(e.getMessage());
            }
            //删除原来的图片
            String mag = sh.getStallsPictures();
            try {
                ImageUtil.delete(mag, ImageCatalogue.Stalls_Catalogue);
            } catch (Exception e) {
            }
            sh.setStallsPictures(s);
        }
        stallsDao.save(sh);
    }

    @Override
    public void save(Stalls sh) {
        stallsDao.save(sh);
    }

    @Override
    public void deleteById(Integer id) {
        Stalls stalls = stallsDao.findById(id).get();
        deletePic(id);
        stalls.setState(0);
        stallsDao.save(stalls);
    }

    @Override
    public void deleteBatch(String ids) {
        ArrayList<Integer> list = StringTOArrayList.toArrayList(ids);
        for (Integer id :
                list) {
            deletePic(id);
        }
        stallsDao.changeBatch(0, list);
    }

    @Override
    public void changeBatch(int state, String ids) {
        ArrayList<Integer> list = StringTOArrayList.toArrayList(ids);
        stallsDao.changeBatch(state, list);
    }

    @Override
    public List<String> findByUserId(String userId) {
        return stallsDao.findByUserId(userId);
    }

    @Override
    public BigInteger dailyRecord(Integer id) {
        return recordDao.findCountByStallsThisDay(id);
    }

    @Override
    public BigInteger weeklyRecord(Integer id) {
        return recordDao.findCountByStallsThisWeek(id);
    }

    @Override
    public BigInteger monthlyRecord(Integer id) {
        return recordDao.findCountByStallsThisMonth(id);
    }

    @Override
    public List<Map<String,BigInteger>> dailyRecordByPoultry(Integer id) {
        return recordDao.findCountByStallsOrderByPoultryThisDay(id);
    }

    @Override
    public List<Map<String,BigInteger>> weeklyRecordByPoultry(Integer id) {
        return recordDao.findCountByStallsOrderByPoultryThisWeek(id);
    }

    @Override
    public List<Map<String, BigInteger>> monthlyRecordByPoultry(Integer id) {
        return recordDao.findCountByStallsOrderByPoultryThisMonth(id);
    }

    @Override
    public List<Map<Object,Object>> dailyRecordByPoultryAndToMark(Integer id) {
        List<Map<Object,Object>> list = recordDao.findCountByStallsOrderByPoultryAndToMarkThisDay(id);
        return list;
    }

    @Override
    public List<Map<Object,Object>> weeklyRecordByPoultryAndToMark(Integer id) {
        return recordDao.findCountByStallsOrderByPoultryAndToMarkThisWeek(id);
    }

    @Override
    public List<Map<Object,Object>> monthlyRecordByPoultryAndToMark(Integer id) {
        return recordDao.findCountByStallsOrderByPoultryAndToMarkThisMonth(id);
    }

    @Override
    public Stalls findByBarcodeMachineId(String s) {
        Optional<BarcodeMachine> optional = barcodeMachineDao.findById(s);
        if (optional.isPresent()) {
            BarcodeMachine barcodeMachine = optional.get();
            String stallsId = barcodeMachine.getStallsId();
            //Stalls one = stallsDao.getOne(Integer.valueOf(stallsId));
            Optional<Stalls> byId = stallsDao.findById(Integer.valueOf(stallsId));
            if (byId.isPresent()) {
                return byId.get();
            }

        }
        return null;
    }

    //根据名字模糊匹配
    @Override
    public List<StallsVO> getByLikeName(String name) {
        List<Stalls> res = stallsDao.getLikeName(1, name);
        return changeToVOList(res);
    }

    @Override
    public List<Object> findAllDTO() {
        List<Stalls> stallsList = stallsDao.findByState(1);
        List<Object> list = new ArrayList<>();
        for (Stalls s :
                stallsList) {
            StallsDownloadDTO dto = new StallsDownloadDTO();
            BeanUtils.copyProperties(s, dto);
            if (s.getUserId() != null && !s.getUserId().equals("")) {
                Person user = personDao.findVO(s.getUserId());
                if (user != null) {
                    dto.setUserName(user.getName());
                    dto.setMobile(user.getMobile());
                    dto.setPhone(user.getPhone());
                }
            }
            if (s.getSlaughterHouseId() != null && !s.getSlaughterHouseId().equals("")) {
                Optional<SlaughterHouse> optional = slaughterHouseDao.findById(Integer.valueOf(s.getSlaughterHouseId()));
                if (optional.isPresent()) {
                    dto.setSlaughterHouseName(optional.get().getName());
                }
            }
            list.add(dto);
        }
        return list;
    }

    @Override
    public void save(List<Object> list, HttpServletRequest request) {
        String creatBy = null;
        try {
            UsersExtends usersExtends = (UsersExtends) request.getAttribute("usersExtends");
            creatBy = usersExtends.getUser().getLoginName();
        } catch (Exception e) {
//            throw new MyException(500, "未找到用户登录信息");
        }
        List<Stalls> stallsList = new ArrayList<>();
        for (Object object :
                list) {
            Stalls s = new Stalls();
            StallsUploadDTO dto = (StallsUploadDTO) object;
            BeanUtils.copyProperties(dto, s);
            if (dto.getUserName() != null && !dto.getUserName().equals("")) {
                Person user = personDao.findByName(dto.getUserName());
                if (user == null) {
                    throw new MyException(500, "负责人姓名有误，未找到负责人");
                }
                s.setUserId(user.getId());
            }
            if (dto.getSlaughterHouseName() == null || "".equals(dto.getSlaughterHouseName())) {
                throw new MyException(500, "未填写市场名称");
            }
            SlaughterHouse slaughterHouse = slaughterHouseDao.findByNameAndState(dto.getSlaughterHouseName(), 1);
            if (slaughterHouse == null) {
                throw new MyException(500, "市场名称有错误，未找到相应的市场");
            }
            s.setSlaughterHouseId(String.valueOf(slaughterHouse.getId()));
            s.setCreateDate(new Date());
            s.setCreateBy(creatBy);
            s.setState(1);
            stallsList.add(s);
        }
        stallsDao.saveAll(stallsList);
    }

    private StallsVO changeToVO(Stalls s) {
        StallsVO vo = new StallsVO();
        BeanUtils.copyProperties(s, vo);
        if (s.getUserId() != null && !s.getUserId().equals("")) {
            Person user = personDao.findVO(s.getUserId());
            if (user != null) {
                vo.setUserName(user.getName());
                vo.setPhone(user.getPhone());
                vo.setUserQq(user.getQq());
                vo.setUserWechat(user.getWechat());
                vo.setUserWechatCode(user.getWechatCode());
            }
        }
        String slaughterHouseId = s.getSlaughterHouseId();
        if (slaughterHouseId != null && !slaughterHouseId.equals("")) {
            Optional<SlaughterHouse> optional1 = slaughterHouseDao.findById(Integer.valueOf(slaughterHouseId));
            if (optional1.isPresent()) {
                vo.setHouseName(optional1.get().getName());
            }
        }
        if (s.getCreateBy() != null && !s.getCreateBy().equals("")) {
            Person user2 = personDao.findVO(s.getCreateBy()); //创建者
            if (user2 != null) {
                vo.setCreateName(user2.getName());
            }
        }
        return vo;
    }

    private List<StallsVO> changeToVOList(List<Stalls> stallsList) {
        List<StallsVO> list = new ArrayList<>();
        for (Stalls s :
                stallsList) {
            list.add(changeToVO(s));
        }
        return list;
    }

    private void deletePic(Integer id) {
        Optional<Stalls> optional = stallsDao.findById(id);
        if (optional.isPresent()) {
            Stalls stalls = optional.get();
            String mag = stalls.getStallsPictures();
            if (mag != null && !mag.equals(""))
                ImageUtil.delete(mag, ImageCatalogue.Stalls_Catalogue);
        }
    }
}
